# --*-- coding:utf-8 --*--

import warnings
warnings.filterwarnings("ignore")
import requests
import datetime
import time
import math
import random
from multiprocessing import Pool
from multiprocessing.dummy import Pool


class prodouct_data_analysis():

	cookies = None
	head = {
			'Host': 'sycm.taobao.com',
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'

	}
	dateRange = None

	new_data = []

	table_and_map = {}

	def dateRanges(self,beginDate, endDate):
	    dates = []
	    dt = datetime.datetime.strptime(beginDate, '%Y-%m-%d')
	    date = beginDate[:]
	    while date <= endDate:
	        dates.append(date)
	        dt = dt + datetime.timedelta(1)
	        date = dt.strftime('%Y-%m-%d')
	    return dates


	# def goods_data_analysis(self):

	# 	#单品数据分析
	# 	dateRange = str(self.dateRange['start_time']) +"|"+ str(self.dateRange['end_time'])
	# 	url = 'https://sycm.taobao.com/bda/items/effect/getItemsEffectDetail.json'

	# 	data = {
	# 			'dateRange':dateRange,
	# 			'dateType':'recent30',
	# 			'device':'0',
	# 			'orderDirection':'false',
	# 			'orderField':'itemPv',
	# 			'page':'1',
	# 			'pageLimit':'10',
	# 			'token':'1a998269c',
	# 			'type':'0',
	# 			'_':'1536721253977'
				
	# 	}

	# 	# 取出第一页单品数据分析里面的黄色数据
	# 	resp = requests.get(url,headers = self.head,cookies = self.cookies,verify=False,params = data)
	# 	pages_data = []		
	# 	for k in resp.json()['data']['data']:
	# 		pages_data.append(k)
	# 	return pages_data

	# #30天加购人数
	# def get_addCart(self,pages_data):

	# 	# 取出单品数据分析里面的蓝色数据加购人数(通过商品id)  
	# 	# for k in pages_data:
	# 	dateRange = str(self.dateRange['start_time']) +"|"+ str(self.dateRange['end_time'])

	# 	itemId = pages_data['itemEffectIndex']['id']

	# 	url = 'https://sycm.taobao.com/bda/itemformto/listFlowFromTo.json'

	# 	data = {
	# 			'algorithm':'0',
	# 			'currentPage':'1',
	# 			'dateRange':dateRange,
	# 			'dateType':'recent30',
	# 			'device':'2',
	# 			'itemId':itemId,
	# 			'pageSize':'10',
	# 			'token':'1a998269c',
	# 			'_':'1536724313120'
	# 	}
	# 	all_addCartBuyerCnt = 0
	# 	# 无线
	# 	wx_resp = requests.get(url,headers = self.head,cookies = self.cookies,verify=False,params = data)
	# 	wx_addCartBuyerCnt = wx_resp.json()['data']['list']
	# 	for i in wx_addCartBuyerCnt:
	# 		all_addCartBuyerCnt =  all_addCartBuyerCnt + i['addCartBuyerCnt']
	# 	time.sleep(random.uniform(1,3))

	# 	# PC 
	# 	data['device'] = '1'
	# 	pc_resp = requests.get(url,headers = self.head,cookies = self.cookies,verify=False,params = data)
	# 	pc_addCartBuyerCnt = pc_resp.json()['data']['list']
	# 	for i in pc_addCartBuyerCnt:
	# 		all_addCartBuyerCnt =  all_addCartBuyerCnt + i['addCartBuyerCnt']
	# 	pages_data['addCartBuyerCnt'] = all_addCartBuyerCnt
	# 	return pages_data

	# def get_mon_data(self):

	# 	all_page_data = self.goods_data_analysis()
		
	# 	pool = Pool(5)
	# 	data = pool.map(self.get_addCart,all_page_data)
	# 	pool.close()
	# 	pool.join()
	# 	self.table_and_map['table'] = data

	# # 每天数据分析
	# def day_prodouct_data(self,date):

	# 	time.sleep(random.uniform(1,5))


	# 	dates = str(date) +"|"+ str(date)
	# 	# 30天每天商品详情
	# 	url = 'https://sycm.taobao.com/bda/items/effect/getItemsEffectDetail.json'

	# 	data = {
	# 			'dateRange':dates,
	# 			'dateType':'recent1',
	# 			'device':'0',
	# 			'orderDirection':'false',
	# 			'orderField':'itemPv',
	# 			'page':'1',
	# 			'pageLimit':'10',
	# 			'token':'1a998269c',
	# 			'type':'0',
	# 			'_':'1536721253977'
				
	# 	}

	# 	# 取出单品数据分析里面的黄色数据
	# 	resp = requests.get(url,headers = self.head,cookies = self.cookies,verify=False,params = data)
	# 	# print (resp.text)   #{"code":5810,"msg":"You must login system first."}
	# 	if resp.json()['code'] == 0:
	# 		pages_data = []
	# 		for k in resp.json()['data']['data']:
	# 			k['statDate'] = date
	# 			pages_data.append(k)
	# 		return pages_data
	# 	elif resp.json()['code'] == 5810 :
	# 		return resp.json()

	# 	else:
	# 		return resp.json()

	# def get_day_addCart(self,data):

	# 	# 取出单品数据分析里面的蓝色数据加购人数(通过商品id)  最近30天的数据
	# 	data_ten = []
	# 	for datas in data:
	# 		dateRange = str(datas['statDate']) +"|"+ str(datas['statDate'])

	# 		itemId = datas['itemEffectIndex']['id']

	# 		url = 'https://sycm.taobao.com/bda/itemformto/listFlowFromTo.json'

	# 		payload = {
	# 				'algorithm':'0',
	# 				'currentPage':'1',
	# 				'dateRange':dateRange,
	# 				'dateType':'day',
	# 				'device':'2',
	# 				'itemId':itemId,
	# 				'pageSize':'10',
	# 				'token':'1a998269c',
	# 				'_':'1536724313120'
	# 		}
	# 		all_addCartBuyerCnt = 0
	# 		# 无线
	# 		wx_resp = requests.get(url,headers = self.head,cookies = self.cookies,verify=False,params = payload)
	# 		# 判断cookies的可用性
	# 		try:
	# 			wx_addCartBuyerCnt = wx_resp.json()['data']['list']
	# 			for i in wx_addCartBuyerCnt:
	# 				all_addCartBuyerCnt =  all_addCartBuyerCnt + i['addCartBuyerCnt']
	# 			time.sleep(random.uniform(1,5))
	# 		except:
	# 			pass

	# 		# PC 
	# 		payload['device'] = '1'
	# 		pc_resp = requests.get(url,headers = self.head,cookies = self.cookies,verify=False,params = payload)
	# 		try:
	# 			pc_addCartBuyerCnt = pc_resp.json()['data']['list']
	# 			for i in pc_addCartBuyerCnt:
	# 				all_addCartBuyerCnt =  all_addCartBuyerCnt + i['addCartBuyerCnt']
	# 			datas['addCartBuyerCnt'] = all_addCartBuyerCnt
	# 			data_ten.append(datas)
	# 		except:
	# 			pass

	# 	return data_ten



	# def main(self):
	# 	#获取最近30天数据
	# 	self.get_mon_data()

	# 	# 获取30天每天数据
	# 	time_list = self.dateRanges(self.dateRange['start_time'],self.dateRange['end_time'])
	# 	pool = Pool(5)
	# 	data = pool.map(self.day_prodouct_data,time_list)
	# 	pool.close()
	# 	pool.join()


	# 	# # 加购人数
	# 	pool = Pool(10)
	# 	addCat_data = pool.map(self.get_day_addCart,data)
	# 	pool.close()
	# 	pool.join()
	# 	self.table_and_map['map'] = addCat_data
	# 	return self.table_and_map

		#Any_day_data(self,dates)
	# def Any_day_data(self,goodsidList):

	# 	# 任意商品任意天数数据
	# 	self.time_list = self.dateRanges(self.dateRange['start_time'],self.dateRange['end_time'])
	# 	pool = Pool(math.ceil(len(self.time_list)/3))
	# 	data = pool.map(self.Serch_Goods,goodsidList)
	# 	pool.close()
	# 	pool.join()
	# 	return 


		# try:
		# 	data[0][0]['code']  # 能读到code说明过期或者商品ID不正确，但是返回的数据不一样
		# 	return data[0]
		# except:
		# 	# # # 加购人数
		# 	pool = Pool(math.ceil(len(self.time_list)/3))
		# 	addCat_data = pool.map(self.get_day_addCart,data)
		# 	pool.close()
		# 	pool.join()
		# 	return addCat_data


	# def SelectGoods(self,goodsid):

	# 	# 选择商品查看数据

	# 	any_data = []

	# 	url = 'https://sycm.taobao.com/bda/items/effect/getItemsEffectDetail.json'

	# 	for date in self.time_list:

	# 		time.sleep(random.uniform(1,3))

	# 		dateRange = dates = str(date) +"|"+ str(date)

	# 		payload = {
	# 			'dateRange':dateRange,
	# 			'dateType':'day',
	# 			'device':'0',
	# 			'keywords':goodsid,
	# 			'orderDirection':'false',
	# 			'orderField':'itemPv',
	# 			'page':'1',
	# 			'pageLimit':'10',
	# 			'token':'c2f4dc7e5',
	# 			'type':'0',
	# 			'_':'1538970721500'
	# 		}

	# 		resp = requests.get(url,headers = self.head,cookies = self.cookies,verify=False,params = payload)
	# 		if resp.json()['code'] == 0:
	# 			for k in resp.json()['data']['data']:
	# 				k['statDate'] = date
	# 				any_data.append(k)
	# 		elif resp.json()['code'] == 5810 :
	# 			any_data.append(resp.json())

	# 		else:
	# 			any_data.append(resp.json())

	# 	return any_data


	def Serch_Goods(self,goodsid):

		''' 品类罗盘里面取数'''

		url = 'https://sycm.taobao.com/cc/cockpit/marcro/item/top.json'

		time_list = self.dateRanges(self.dateRange['start_time'],self.dateRange['end_time'])


		all_day_data = []

		for date in time_list:

			time.sleep(random.uniform(1,3))

			dateRange = dates = str(date) +"|"+ str(date)

			payload = {
				"dateRange":dateRange,
				"dateType":"day",
				"pageSize":"10",
				"page":"1",
				"order":"desc",
				"orderBy":"payAmt",
				"keyword":goodsid,
				"follow":"false",
				"cateId":"",
				"cateLevel":"",
				"guideCateId":"",
				"device":"0",
				"indexCode":"itmUv,itemCartCnt,payItmCnt,payAmt,payRate",
				"_":"1540976730914",
				"token":"4a17c83e2"

			}
			resp = requests.get(url,headers = self.head,cookies = self.cookies,verify=False,params = payload)
			all_day_data.append(resp.json())
		return all_day_data

if __name__ == '__main__':
	
	prodouct_data_analysis = prodouct_data_analysis()

	prodouct_data_analysis.dateRange = {"start_time":'2018-11-03',"end_time":'2018-11-03'}

	#过期
	# prodouct_data_analysis.cookies = {"tg":"0","_tb_token_":"ebe5ef38b536e","_nk_":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","cookie17":"UNN0nnQ5PzBj6g%3D%3D","uc1":"cookie16=U%2BGCWk%2F74Mx5tgzv3dWpnhjPaQ%3D%3D&tmb=1&cookie21=W5iHLLyFfoWm&cookie15=UtASsssmOIJ0bQ%3D%3D&existShop=true&pas=0&cookie14=UoTYNk7%2F%2Fv2V0A%3D%3D&tag=8&lng=zh_CN","sg":"%E5%BA%9702","lgc":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","tracknick":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","csg":"eb5ca3c8","skt":"a934a0a2cbdba5ee","uc3":"vt3=F8dByRjO3UoTnhoXJOw%3D&id2=UNN0nnQ5PzBj6g%3D%3D&nk2=sHmGuBnK6YrEuQ%3D%3D&lg2=UIHiLt3xD8xYTw%3D%3D","_cc_":"UIHiLt3xSw%3D%3D","unb":"3397628220","v":"0","mt":"np=","isg":"BNnZ8JPX5pFAuroFDKAfb7bL5MyzZs0YglUHm_uOVYB_AvmUQ7bd6EeQAEh0oWVQ","existShop":"MTU0MDk3NDUxMA%3D%3D","cna":"cJFTFKDA9n4CAcFwhT5/XTa9","cookie1":"UNaOmjEdkzPF0d%2BKqRdPBjspDZcJ%2BrbnVjjQlzW63YA%3D","_l_g_":"Ug%3D%3D","JSESSIONID":"56A9866A734EA7CB5CB29CE3E7FF6CE7","dnk":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","t":"b6bcbcb374acbd2926c83e935539888c","cookie2":"1ca02635ad10e5fdb809de88c8818b3e"}

	# 过期
	prodouct_data_analysis.cookies =  {"_tb_token_":"e56deee0bbde5","unb":"3397628220","tracknick":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","tg":"0","v":"0","dnk":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","existShop":"MTU0MTczMjMzOA%3D%3D","mt":"np=","uc3":"vt3=F8dByR%2FJztFAbFuuNtw%3D&id2=UNN0nnQ5PzBj6g%3D%3D&nk2=sHmGuBnK6YrEuQ%3D%3D&lg2=URm48syIIVrSKA%3D%3D","t":"cb0e64096ce0fef85a43f4f40874929a","cna":"15ZiFBhnImkCAcFwhT7OdcJz","sg":"%E5%BA%9702","uc1":"cookie16=URm48syIJ1yk0MX2J7mAAEhTuw%3D%3D&tmb=1&cookie21=VFC%2FuZ9aj38X&cookie15=UIHiLt3xD8xYTw%3D%3D&existShop=true&pas=0&cookie14=UoTYN4Y2kDKdJA%3D%3D&tag=8&lng=zh_CN","skt":"407343cc6041ab22","cookie1":"UNaOmjEdkzPF0d%2BKqRdPBjspDZcJ%2BrbnVjjQlzW63YA%3D","_cc_":"V32FPkk%2Fhw%3D%3D","isg":"BH19DMuv-njcCl6UWJDdtJdNgNB3GrFsjkHjdz_CuVQDdp2oB2rBPEukJCQwbckk","csg":"0e1d74aa","cookie2":"1a2898b9d133f217be78e8bf3c594f88","_l_g_":"Ug%3D%3D","JSESSIONID":"5682972FC455D0F98B719ACDA1FD4034","cookie17":"UNN0nnQ5PzBj6g%3D%3D","lgc":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97","_nk_":"%5Cu5FA1%5Cu679C%5Cu65D7%5Cu8230%5Cu5E97"}


	goodsidList = [569541384926]

	print (prodouct_data_analysis.Serch_Goods(goodsidList))
